﻿using System;
using System.Collections;
using System.Collections.Generic;
using com.guojin.mj.net.message.game;
using UnityEngine;
using UnityEngine.UI;

public class Player : MonoBehaviour
{
    public string userName;
    public string avatar;
    public Texture headTexture; //玩家头像暂存
    public int sex;
    public int gold;
    private int totalScore;
    public int locationIndex;
    public int userId;
    public string ip;
    public bool isMiddleJoin;
    public bool online;
    public string longitude;
    public string latitude;
    public string approver;

    public string cardType;
    private int betScore;
    public int betState;
    private int dealState;
    private int settleScore;
    public readonly List<int> handCardsList = new List<int>();

    public  GameObject playerHeadObj;
    public  GameObject playerCardObj;
    public GameObject readyObj;
    public GameObject cardTypeObj;
    public GameObject zhuangObj;
    public GameObject betScoreObj;

    #region    //自动属性
    public int SettleScore
    {
        get { return settleScore; }
        set
        {
            settleScore = value;
            if (settleScore  != 0 && GameRoomModel.GetInstance().RoomState == 4)
            {
                ShowSettleScore(true, settleScore);
            }
            else
            {
                ShowSettleScore(false, 0);
            }
        }
    }

    public int BetScore
    {
        get { return betScore; }
        set
        {
            betScore = value;
            if (betScore > 0)
            {
                ShowBetScore(true, betState, betScore);
            }
            else if(betScore == 0)
            {
                ShowBetScore(false, 0, 0);
            }
        }
    }

    public int TotalScore
    {
        get { return totalScore; }
        set
        {
            totalScore = value;
            ShowTotalScore(totalScore);
        }
    }

    public int DealState
    {
        get { return dealState; }
        set
        {
            dealState = value;

            if (dealState == 0)
            {
                ShowReady(false);
            }
            else if(dealState == 1)
            {
                ShowReady(true);
            }
        }
    }
    #endregion

    #region//初始化玩家信息 头像 名字（设置引用）
    public void InitHeadAndNameSaveUserInfo(GameUserInfoRet GameUser)                                              //初始化玩家头像信息
    {
        if (GameUser.locationIndex >= 0)
        {
            SetReferenceToObj();
            SaveUserInfoToThis(GameUser);
            playerHeadObj.GetComponent<PlayerHeadPage>().InitPlayerHead(GameUser);         //生成头像 名字
            SetCardGroupOwnLocationIndex();                                                                                  //设置手牌拥有者编号
        }       
    }

    public void SaveUserInfoToThis(GameUserInfoRet GameUser)
    {
        userName = GameUser.userName;
        avatar = GameUser.avatar;
        sex = GameUser.sex;
        gold = GameUser.gold;
        locationIndex = GameUser.locationIndex;
        userId = GameUser.userId;
        ip = GameUser.ip;
        isMiddleJoin = GameUser.isMiddleJoin;
        online = GameUser.online;
        TotalScore = GameUser.totalScore;
        longitude = GameUser.longitude;
        latitude = GameUser.latitude;
        approver = GameUser.approver;
    }

    private void SetReferenceToObj()
    {
        playerHeadObj = gameObject;
        playerCardObj = playerHeadObj.transform.parent.parent.FindChild("cardPoint/playerCard").gameObject;
        if (playerHeadObj.transform.parent.parent.name == "player0")
            playerCardObj.transform.FindChild("cardGroup").GetComponent<GridLayoutGroup>().spacing = new Vector2(5, 0);
             
        readyObj = playerHeadObj.transform.parent.parent.FindChild("ready").gameObject;
        cardTypeObj = playerHeadObj.transform.parent.parent.FindChild("cardType").gameObject;
        zhuangObj = playerHeadObj.transform.parent.parent.FindChild("zhuang").gameObject;
        betScoreObj = playerHeadObj.transform.parent.parent.FindChild("betScore").gameObject;
    }

    private void SetCardGroupOwnLocationIndex()
    {
        playerCardObj.transform.FindChild("cardGroup").gameObject.GetComponent<PlayerCardController>().ownPlayerLocationIndex =
            locationIndex;
    }
    #endregion


    #region //设置玩家牌局信息  牌组，分数，下注数，结算分等
    public void InitPlayerChapterInfo(UserChapterInfoRet ucir)    //初始化玩家牌局信息（断线重连使用）
    {
            TotalScore = ucir.TotalScore;
            cardType = ucir.CardType;
            DealState = ucir.DealState;
            AddCards(ucir.Cards);
            betState = ucir.BetState;
            BetScore = ucir.BetScore;
            SettleScore = ucir.SettlementScore;
    }

    //显示牌型， 准备， 庄，下注分
    public void ShowCardType(bool show, string cardtype)
    {
        if (show)
        {
            if (cardtype == "") 
            {
                cardTypeObj.GetComponent<Image>().sprite = Resources.Load<Sprite>("CardType/" + cardType);      
            }
            else
            {
                cardTypeObj.GetComponent<Image>().sprite = Resources.Load<Sprite>("CardType/" + cardtype);
            }
            cardTypeObj.SetActive(true);
        }
        else
        {
            cardTypeObj.SetActive(false);
        }
    }

    public void ShowReady(bool show)
    {
        if (show)
        {
            readyObj.SetActive(true);
        }
        else
        {
            readyObj.SetActive(false);
        }
    }

    public void ShowZhuang(bool show)
    {
        if (show)
        {
            zhuangObj.SetActive(true);
        }
        else
        {
            zhuangObj.SetActive(false);
        }
    }

    public void ShowBetScore(bool show, int betState, int betScore)
    {
        if (show)
        {
            betScoreObj.SetActive(true);
            betScoreObj.transform.GetChild(0).GetComponent<Text>().text = betScore.ToString();

            if (betState == 1)
            {
                betScoreObj.GetComponent<Image>().sprite = Resources.Load<Sprite>("UI/GameRoom/积分1");
            }
            else if (betState == 2)
            {
                betScoreObj.GetComponent<Image>().sprite = Resources.Load<Sprite>("UI/GameRoom/积分2");
            }
        }
        else
        {
            betScoreObj.SetActive(false);
        }
    }

    private void ShowTotalScore(int totalSocre)
    {
        if (locationIndex >= 0)
        {        
            playerHeadObj.GetComponent<PlayerHeadPage>().SetTotalScoreText(totalSocre);
        }       
    }

    public void ShowSettleScore(bool show, int num)
    {
        playerHeadObj.GetComponent<PlayerHeadPage>().SetSettleScore(show, num);
    }
    #endregion


    #region  //牌局开始初始化方法
    public void GameReadyInitUser()
    {
        ClearHandCardsList();
        ClearHandCardsObj();
        ShowCardType(false,"");
        ShowBetScore(false, 0, 0);
        ShowZhuang(false);
        ShowReady(false);
        ShowSettleScore(false, 0);
        playerCardObj.transform.FindChild("cardGroup").GetComponent<PlayerCardController>().list.Clear();
        dealState = 0;
        betState = 0;
    }

    private void ClearHandCardsList()
    {
        //初始化手牌列表
        handCardsList.Clear();
    }

    private void ClearHandCardsObj()
    {
        Debug.Log(playerCardObj);
        Debug.Log(playerCardObj.transform.FindChild("cardGroup"));
        if (playerCardObj.transform.FindChild("cardGroup").childCount != 0)
            TooL.DestroyAllChildren(playerCardObj.transform.FindChild("cardGroup").gameObject); //清空手牌(每次发牌都)
    }
    #endregion


    #region//添加手牌 亮牌
    public void AddCards(int[] cards)
    {
        BreakOnlineAddCardsToHandCardsList(cards);
        BreakOnlineAddCardsObjToCardGroup(cards);
    }

    private void BreakOnlineAddCardsToHandCardsList(int[] cards)
    {
        for (int i = 0; i < cards.Length; i++)
        {
            handCardsList.Add(cards[i]);
        }
    }

    private void  BreakOnlineAddCardsObjToCardGroup(int[] cards)
    {
        for (int i = 0; i < cards.Length; i++)
        {
            var temp = TooL.LoadPrefab(playerCardObj.transform.FindChild("cardGroup").gameObject, "Card");
            temp.GetComponent<Card>().cardValue = cards[i];
            temp.name = cards[i].ToString();
            temp.GetComponent<LayoutElement>().ignoreLayout = false;
            CardLoadValueOrBack(temp);
        }

        if (GameRoomModel.GetInstance().RoomState == 4)
        {
            StartCoroutine("showDistanceLater");
        }
    }

    IEnumerator showDistanceLater()
    {
        yield return new WaitForSeconds(1f);

        if (GameRoomModel.GetInstance().RoomState == 4)
        {
            ShowCardDistance(cardType);
        }    
    }


    private void CardLoadValueOrBack(GameObject temp)
    {
        Transform group = playerCardObj.transform.FindChild("cardGroup");

        if (GameRoomModel.GetInstance().RoomState == 1)           // 房间状态1 抢庄
        {
            temp.GetComponent<Card>().LoadBackSprite();
        }
        else if (GameRoomModel.GetInstance().RoomState == 2)    //房间状态2 下注
        {
            temp.GetComponent<Card>().LoadBackSprite();
        }
        else if(GameRoomModel.GetInstance().RoomState == 3)     //房间状态3 出牌 如果是自己显示正面，如果是别人显示背面
        {
            if (GameData.GetInstance().locationIndex == locationIndex) 
            {
                temp.GetComponent<Card>().LoadValueSprite();
            }
            else
            {
                temp.GetComponent<Card>().LoadBackSprite();
            }         
        }
        else if(GameRoomModel.GetInstance().RoomState == 4)    //房间状态4 亮牌
        {
            temp.GetComponent<Card>().LoadValueSprite();
        }
    }

    public void ShowCardBack()
    {
            var temp = playerCardObj.transform.FindChild("cardGroup");

        for (var i = 0; i < temp.childCount; i++)
        {
            temp.GetChild(i).GetComponent<Card>().LoadBackSprite();
        }
    }

    public void ShowCardValue()
    {
        var temp = playerCardObj.transform.FindChild("cardGroup");

        for (var i = 0; i < temp.childCount; i++)
        { 
                temp.GetChild(i).GetComponent<Card>().LoadValueSprite();
        }
    }
    public void ShowCardValueFour()
    {
        var temp = playerCardObj.transform.FindChild("cardGroup");

        for (var i = 0; i < 4; i++)
        {
            temp.GetChild(i).GetComponent<Card>().LoadValueSprite();
        }
    }
    public void ShowCardBaseCardType(int[] cards)
    {
        var temp = playerCardObj.transform.FindChild("cardGroup");

        for (var i = 0; i < temp.childCount; i++)
        {
            temp.GetChild(i).GetComponent<Card>().LoadSpriteValueBaseValue(cards[i]);
        }
    }

    public void ShowCardDistance(string  cardType)
    {
        switch (GameController.GetInstance().intArr[locationIndex])
        {       
            case 0:
                break;
            case 1:
            case 2:
                Debug.Log("玩家"+locationIndex+ "cardType" +1);
                ShowCardMoveCard(1, cardType);
                break;
            case 3:
            case 4:
            case 5:
                Debug.Log("玩家" + locationIndex + "cardType" + 2);
                ShowCardMoveCard(2, cardType);
                break;
        }
    }

    //1左移动   2右移动
    private void ShowCardMoveCard(int num, string cardType)
    {
        Debug.Log("这里牌发生位移！");

        for (int i = 0; i < 5; i++)
        {
            playerCardObj.transform.FindChild("cardGroup").GetChild(i).GetComponent<LayoutElement>().ignoreLayout = true;
        }

        if (cardType == "散牌" || cardType == "牛牛" || cardType == "五花" || cardType == "五小")
        {
            return;
        }
        else if(cardType == "炸弹")
        {
            if (num == 1)
            {
                for (int i = 0; i < 4; i++)
                {
                    playerCardObj.transform.FindChild("cardGroup").GetChild(i).position = new Vector3(playerCardObj.transform.FindChild("cardGroup").GetChild(i).position.x-0.4f, 
                        playerCardObj.transform.FindChild("cardGroup").GetChild(i).position.y, playerCardObj.transform.FindChild("cardGroup").GetChild(i).position.z);
                }
            }
            else if(num == 2)
            {
                playerCardObj.transform.FindChild("cardGroup").GetChild(4).position = new Vector3(playerCardObj.transform.FindChild("cardGroup").GetChild(4).position.x + 0.4f,
                  playerCardObj.transform.FindChild("cardGroup").GetChild(4).position.y, playerCardObj.transform.FindChild("cardGroup").GetChild(4).position.z);
            }
        }
        else 
        {
            if (num == 1)
            {
                for (int i = 0; i < 3; i++)
                {
                    playerCardObj.transform.FindChild("cardGroup").GetChild(i).position = new Vector3(playerCardObj.transform.FindChild("cardGroup").GetChild(i).position.x - 0.4f,
                        playerCardObj.transform.FindChild("cardGroup").GetChild(i).position.y, playerCardObj.transform.FindChild("cardGroup").GetChild(i).position.z);
                }
            }
            else if (num == 2)
            {
                for (int i = 3; i < 5; i++)
                {
                    playerCardObj.transform.FindChild("cardGroup").GetChild(i).position = new Vector3(playerCardObj.transform.FindChild("cardGroup").GetChild(i).position.x +0.4f,
                        playerCardObj.transform.FindChild("cardGroup").GetChild(i).position.y, playerCardObj.transform.FindChild("cardGroup").GetChild(i).position.z);
                }
            }
        }
    }


    public void ShowCardPitchBaseCardType(string cardType)
    {
        var temp = playerCardObj.transform.FindChild("cardGroup");

        for (var i = 0; i < temp.childCount; i++)
        {
            if (cardType == "五小" || cardType == "五花" || cardType == "牛牛")
            {
                temp.GetChild(i).GetComponent<Card>().ShowPitchOn(true);
            }
            else if (cardType == "炸弹")
            {
                if (i < 4)
                {
                    temp.GetChild(i).GetComponent<Card>().ShowPitchOn(true);
                }
                else
                {
                    temp.GetChild(i).GetComponent<Card>().ShowPitchOn(false);
                }
            }
            else if (cardType == "散牌")
            {
                temp.GetChild(i).GetComponent<Card>().ShowPitchOn(false);
            }
            else                                                                          //普通牛
            {
                if (i < 3)
                {
                    temp.GetChild(i).GetComponent<Card>().ShowPitchOn(true);
                }
                else
                {
                    temp.GetChild(i).GetComponent<Card>().ShowPitchOn(false);
                }
            }
        }
    }

    public int[] HandCardsListToInt()
    {
        int[] arr = new int[5];
        for (int i = 0; i < 5; i++)
        {
            arr[i] = handCardsList[i];
        }
        return arr;
    }

    #endregion


    public void ShowDownTime(bool show, float num = 150)
    {
        playerHeadObj.GetComponent<PlayerHeadPage>().SetDownTime(show, num);
    }

    public float  GetDownTime()
    {
        return playerHeadObj.GetComponent<PlayerHeadPage>().GetDownTime();
    }

    //玩家下注
    public void PlayerBet(int betNum)
    {
        //TotalScore -= betNum;
    }
    
    //退出房间删除头像
    public void ExitRoomDeleteHead()
    {
        Destroy(playerHeadObj.gameObject);
        Destroy(playerCardObj.gameObject);
        ShowBetScore(false, 0, 0);
        ShowCardType(false,"");
        ShowReady(false);
        ShowZhuang(false);
    }  
}